package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.*;
import com.luo.backend.service.GroupBuyingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 团购控制器
 */
@RestController
@RequestMapping("/api/v1/group-buying")
public class GroupBuyingController {
    
    private static final Logger logger = LoggerFactory.getLogger(GroupBuyingController.class);
    
    @Autowired
    private GroupBuyingService groupBuyingService;
    
    /**
     * 发起团购
     */
    @PostMapping
    public ApiResponse<GroupBuyingResponse> createGroupBuying(@Valid @RequestBody CreateGroupBuyingRequest request) {
        try {
            Long userId = getCurrentUserId();
            GroupBuyingResponse response = groupBuyingService.createGroupBuying(userId, request);
            return ApiResponse.success("团购发起成功", response);
        } catch (Exception e) {
            logger.error("发起团购失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 参与团购
     */
    @PostMapping("/{id}/join")
    public ApiResponse<GroupBuyingResponse> joinGroupBuying(
            @PathVariable Long id,
            @Valid @RequestBody JoinGroupBuyingRequest request) {
        try {
            Long userId = getCurrentUserId();
            GroupBuyingResponse response = groupBuyingService.joinGroupBuying(userId, id, request);
            return ApiResponse.success("参与团购成功", response);
        } catch (Exception e) {
            logger.error("参与团购失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取团购列表
     */
    @GetMapping
    public ApiResponse<Map<String, Object>> getGroupBuyingList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long merchantId) {
        try {
            Long currentUserId = getCurrentUserIdOptional();
            Map<String, Object> result = groupBuyingService.getGroupBuyingList(merchantId, page, size, currentUserId);
            return ApiResponse.success("success", result);
        } catch (Exception e) {
            logger.error("获取团购列表失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取团购详情
     */
    @GetMapping("/{id}")
    public ApiResponse<GroupBuyingResponse> getGroupBuyingDetail(@PathVariable Long id) {
        try {
            Long currentUserId = getCurrentUserIdOptional();
            GroupBuyingResponse response = groupBuyingService.getGroupBuyingDetail(id, currentUserId);
            return ApiResponse.success("success", response);
        } catch (Exception e) {
            logger.error("获取团购详情失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取我的团购
     */
    @GetMapping("/my")
    public ApiResponse<Map<String, Object>> getMyGroupBuying(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Long userId = getCurrentUserId();
            Map<String, Object> result = groupBuyingService.getMyGroupBuying(userId, page, size);
            return ApiResponse.success("success", result);
        } catch (Exception e) {
            logger.error("获取我的团购失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 取消团购
     */
    @PutMapping("/{id}/cancel")
    public ApiResponse<GroupBuyingResponse> cancelGroupBuying(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            GroupBuyingResponse response = groupBuyingService.cancelGroupBuying(userId, id);
            return ApiResponse.success("团购取消成功", response);
        } catch (Exception e) {
            logger.error("取消团购失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取可团购商品
     */
    @GetMapping("/foods")
    public ApiResponse<Map<String, Object>> getGroupBuyingFoods(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long merchantId) {
        try {
            Map<String, Object> result = groupBuyingService.getGroupBuyingFoods(merchantId, page, size);
            return ApiResponse.success("success", result);
        } catch (Exception e) {
            logger.error("获取可团购商品失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 取消参与团购
     */
    @DeleteMapping("/{id}/leave")
    public ApiResponse<GroupBuyingResponse> leaveGroupBuying(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            GroupBuyingResponse response = groupBuyingService.leaveGroupBuying(userId, id);
            return ApiResponse.success("取消参与团购成功", response);
        } catch (Exception e) {
            logger.error("取消参与团购失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取我参与的团购列表
     */
    @GetMapping("/my-participations")
    public ApiResponse<Map<String, Object>> getMyParticipations(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Long userId = getCurrentUserId();
            Map<String, Object> result = groupBuyingService.getMyParticipations(userId, page, size);
            return ApiResponse.success("success", result);
        } catch (Exception e) {
            logger.error("获取我参与的团购列表失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取团购活动参与者列表
     */
    @GetMapping("/{id}/participants")
    public ApiResponse<List<GroupBuyingResponse.ParticipantResponse>> getActivityParticipants(@PathVariable Long id) {
        try {
            List<GroupBuyingResponse.ParticipantResponse> participants = groupBuyingService.getActivityParticipants(id);
            return ApiResponse.success("success", participants);
        } catch (Exception e) {
            logger.error("获取团购参与者列表失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            try {
                return Long.parseLong(authentication.getName());
            } catch (NumberFormatException e) {
                throw new RuntimeException("用户未登录");
            }
        }
        throw new RuntimeException("用户未登录");
    }
    
    /**
     * 获取当前用户ID（可选）
     */
    private Long getCurrentUserIdOptional() {
        try {
            return getCurrentUserId();
        } catch (Exception e) {
            return null;
        }
    }
}
